<?php


namespace App\Logic\Account\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Event\Event;
use App\Model\Account\RechargeModel;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberScoreModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\ORM\DbManager;

class SubmitMemberRechargeForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $username;
    public $amout;
    public $score;
    public $recharge_state;
    public $payment_type;
    public $payment_state;
    public $payment_content;
    public $created_at;


    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'amout'           => ['required|numeric', '充值金额', '充值金额错误'],
            'payment_type'    => ['required', '充值方式', '充值方式错误'],
            'payment_content' => ['required', '支付凭证', '支付凭证错误'],
        ];
    }

    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();
        $validator->addColumn('payment_type')->inArray([RechargeModel::PAYMENT_BINANCE, RechargeModel::PAYMENT_TRX]);
        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
        $this->user_id = UserIdentityHelper::getId();

        return true;
    }

    public function submit()
    {
        $this->validate();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            //添加表
            $insertData = [
                'user_id'         => $this->user_id,
                'amout'           => $this->amout,
                'score'           => 0,
                'recharge_state'  => RechargeModel::INPROGRESS,
                'payment_type'    => $this->payment_type,
                'payment_state'   => RechargeModel::UNPAID,
                'payment_content' => $this->payment_content,
            ];

            //插入数据库
            $res = RechargeModel::insertData($insertData);
            $id  = $res->lastQueryResult()->getLastInsertId();

            DbManager::getInstance()->commitWithCount('write');

            $returnData = ['id' => $id];

            $result = $this->success($returnData);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '下单错误');
            throw $e;
        }
    }

}
